<template>
  <div class="vue-container">
    <el-dialog :visible.sync="resetPasswordVisible" title="重置密码" width="450px">
      <el-form
        ref="resetForm"
        v-loading="loading"
        :model="resetPasswordForm"
        status-icon
        :rules="resetRules"
        :size="size"
        label-width="90px"
        :show-message="false"
      >
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="resetPasswordForm.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model.trim="resetPasswordForm.password" show-password autocomplete="off" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="resetPasswordVisible = false">取消</el-button>
        <el-button v-throttle :size="size" :loading="loading" type="primary" @click="resetPasswordSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mixin } from '@/views/pages/mixin/save'
import md5 from 'js-md5'
import { validPassword } from '@/utils/validate'
export default {
  name: 'ResetPassword',
  mixins: [mixin],
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'))
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度在6-20位之间'))
      } else if (!validPassword(value)) {
        callback(new Error('密码格式不正确，仅支持字母、数字和下划线'))
      } else {
        callback()
      }
    }
    return {
      resetPasswordVisible: false, //  重置密码弹窗
      resetPasswordForm: { }, //  重置密码表单
      resetRules: { // 重置表单校验
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 弹出窗口加载
    openDialog(row) {
      this.resetPasswordForm = {
        id: row.id,
        username: row.username,
        password: ''
      }
      this.resetPasswordVisible = true
    },
    // 提交重置密码
    resetPasswordSubmit() {
      this.$refs['resetForm'].validate((valid, obj) => {
        if (valid) {
          this.loading = true
          const form = {
            id: this.resetPasswordForm.id,
            password: md5(this.resetPasswordForm.password)
          }
          this.funs['resetPassword'](form).then((res) => {
            this.$message({ message: '重置成功', type: 'success' })
            this.resetPasswordVisible = false
          }).finally(() => {
            this.loading = false
          })
        } else {
          const field = []
          for (const key in obj) {
            field.push(obj[key][0].message)
          }
          this.$message.error(field[0])
          return false
        }
      })
    }
  }
}
</script>
